package com.cyou.qb.admin.web;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cyou.nad.utils.MD5;
import com.cyou.qb.common.domain.QiangbaAdmin;
import com.cyou.qb.common.service.AccountService;
import com.cyou.qb.system.AdminUserContext;

/**
 * <p>LoginController</p>
 * <p>
 * Description:登陆、登出、密码修改
 * </p>
 *
 * @author lidongwei
 * @version 
 * @since 2012-9-21
 */
@Controller
@RequestMapping(value = "/login")
public class LoginController extends BaseController {
	@Autowired
	private AccountService accountService;

	@RequestMapping(value = "/index")
	public String index(Model model, HttpServletRequest request, HttpServletResponse response) {
		return "login";
	}

	/**
	 * 用户登陆时进行检验，验证是否能够成功登陆
	 * Description
	 * @author lidongwei
	 * @since 2012-10-30
	 */
	@RequestMapping(value = "/checklogin")
	public String checklogin(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			String loginName = request.getParameter("loginName");
			String password = request.getParameter("loginPassword");
			if (StringUtils.isNotEmpty(loginName) && StringUtils.isNotEmpty(password)) {
				String passwordMD5 = MD5.encode(password);
				QiangbaAdmin qiangbaAdmin = accountService.checkLogin(loginName, passwordMD5);
				if (qiangbaAdmin != null) {
					Date lastTime = qiangbaAdmin.getLastTime();
					String lastIp = qiangbaAdmin.getLastIp();

					qiangbaAdmin.setLastIp(getRequest().getRemoteAddr());
					qiangbaAdmin.setLastTime(new Date());
					//写入数据库
					accountService.updateOneAccount(qiangbaAdmin);

					qiangbaAdmin.setLastTime(lastTime);
					qiangbaAdmin.setLastIp(lastIp);
					setUserContext(qiangbaAdmin);
					return "redirect:/activity/index.do";
				}
			}
			//登陆失败进入,具体
			model.addAttribute("error", "用户名或密码错误");
			return "login";
		} catch (Exception e) {
			print(response, "error:" + e);
			return null;
		}
	}

	private void setUserContext(QiangbaAdmin qiangbaAdmin) {
		AdminUserContext context = new AdminUserContext();
		try {
			PropertyUtils.copyProperties(context, qiangbaAdmin);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("登录时 复制属性出错", e);
		}
		context.setAdminId(qiangbaAdmin.getAdminId());
		context.setSystemName("qiangba_admin");
		context.setUserIP(getRequest().getRemoteAddr());
		getSession().setAttribute("loginedUser", context);
	}

	/**
	 * 登离
	 * Description
	 * @author lidongwei
	 * @since 2012-10-30
	 */
	@RequestMapping(value = "/logout")
	public String logout(Model model, HttpServletRequest request, HttpServletResponse response) {
		request.getSession().removeAttribute("loginedUser");
		return index(model, request, response);
	}

	/**
	 * 修改密码
	 */
	@RequestMapping(value = "/changePassword")
	public String changePassword(Model model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			//从上下文获取用户信息
			QiangbaAdmin qiangbaAdmin = (QiangbaAdmin) request.getSession().getAttribute("loginedUser");
			//从页面获取输入信息
			String originalPass = StringUtils.trimToEmpty(request.getParameter("originalPass"));
			String newPass = StringUtils.trimToEmpty(request.getParameter("newPass"));
			//断言进行错误处理
			Assert.hasText(newPass, "密码不能为空");
			Assert.hasText(originalPass, "密码不能为空");
			Assert.notNull(qiangbaAdmin, "用户不存在请重新登录");
			//判断输入原始密码是否错误
			String userPassword = qiangbaAdmin.getPassword();
			String originalPassMD5 = MD5.encode(originalPass);
			if (originalPassMD5.equals(userPassword)) {
				int aid = -1;
				if (qiangbaAdmin != null)
					aid = qiangbaAdmin.getAdminId();
				accountService.updatePassword(aid, MD5.encode(newPass));
				qiangbaAdmin.setPassword(MD5.encode(newPass));
				print(response, "1");
			} else {
				print(response, "error:原密码错误");
			}
			return null;
		} catch (Exception e) {
			log.error("修改密码出错", e);
			print(response, "error:" + e.getMessage());
			return null;
		}
	}
}